<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish">
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
        v-model:value="ruleForm.alloy_code"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in alloyCodeSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="组织结构" name="organization_structure">
      <a-input v-model:value="ruleForm.organization_structure" />
    </a-form-item>
    
    <a-form-item label="第二相形态" name="second_phase">
      <a-upload
        :fileList="ruleForm.SecondPhaseFileList"
        :beforeUpload="beforeSecondPhaseUpload"
        :headers="headers"
        @change="handleSecondPhaseChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>

    <a-form-item label="晶粒形态" name="grain_morphology">
      <a-upload
        :fileList="ruleForm.GrainMorphologyFileList"
        :beforeUpload="beforeGrainMorphologyUpload"
        :headers="headers"
        @change="handleGrainMorphologyChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>
    
    <a-form-item label="平均晶粒尺寸(μm,nm)" name="average_grain_size">
      <a-input v-model:value="ruleForm.average_grain_size" />
    </a-form-item>
    <a-form-item label="第二相尺寸(μm,nm)" name="second_phase_size">
      <a-input v-model:value="ruleForm.second_phase_size" />
    </a-form-item>
    <a-form-item label="断裂类型" name="fracture_type">
      <a-input v-model:value="ruleForm.fracture_type" />
    </a-form-item>

    <a-form-item label="断口形貌" name="fracture_morphology">
      <a-upload
        :fileList="ruleForm.FractureMorphologyFileList"
        :beforeUpload="beforeFractureMorphologyUpload"
        :headers="headers"
        @change="handleFractureMorphologyChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>

    <a-form-item label="腐蚀形貌" name="corrosion_morphology">
      <a-upload
        :fileList="ruleForm.CorrosionMorphologyFileList"
        :beforeUpload="beforeCorrosionMorphologyUpload"
        :headers="headers"
        @change="handleCorrosionMorphologyChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>

    <a-form-item label="氧化形貌" name="oxidation_morphology">
      <a-upload
        :fileList="ruleForm.OxidationMorphologyFileList"
        :beforeUpload="beforeOxidationMorphologyUpload"
        :headers="headers"
        @change="handleOxidationMorphologyChange"
      >
        <a-button>
          <upload-outlined />
          选择
        </a-button>
      </a-upload>
    </a-form-item>




    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditMicroStructure',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {

    // validStr 不包含空格
    let isValidStr = (str) => {
      return str.indexOf(" ") === -1;
    };
    let validateSampleName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入样品名称");
      } else {
        if (!isValidStr(value)) {
          return Promise.reject("样品名称含有非法字符");
        }
        return Promise.resolve();
      }
    };

    let validateAlloyName = async (rule, value) => {
      if (value === '') {
        return Promise.reject('请选择合金代码')
      }
    }
    return {
      ruleForm: {
        sample_name: '',
        alloy_code: '',
        organization_structure: '',
        average_grain_size: '',
        second_phase_size: '',
        fracture_type: '',

        SecondPhaseFileList: [],
        GrainMorphologyFileList: [],
        FractureMorphologyFileList:[],
        CorrosionMorphologyFileList:[],
        OxidationMorphologyFileList:[],
      },
      rules: {
        sample_name: [
          {
            validator: validateSampleName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
       ],
        alloy_code: [
          {
            validator: validateAlloyName,
            trigger: 'change',
            required: true,
            whiteSpace: true,
          }
        ],
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      alloyCodeSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {

      this.alloyCodeSelectionOptions = []
      this.axios
        .get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.alloyCodeSelectionOptions.push({
              url: data[i].url,
              label: data[i].alloy_code,
            })
          }
          this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
          if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data

                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.alloy_code = data.alloy_code
                this.ruleForm.organization_structure = data.organization_structure
                //第二相形态文件
                //晶粒形态文件
                this.ruleForm.average_grain_size = data.average_grain_size
                this.ruleForm.second_phase_size = data.second_phase_size
                this.ruleForm.fracture_type = data.fracture_type
                //this.ruleForm.fracture_morphology = data.fracture_morphology
                //腐蚀形貌文件
                //氧化形貌文件
                if (data.SecondPhaseFileList !== '') {
                  this.ruleForm.SecondPhaseFileList.push({
                    uid: '-1',
                    name: data.second_phase_filename,
                  })
                }
                if (data.GrainMorphologyFileList !== '') {
                  this.ruleForm.GrainMorphologyFileList.push({
                    uid: '-2',
                    name: data.graion_morphology_filename,
                  })
                }
                if (data.FractureMorphologyFileList !== '') {
                  this.ruleForm.FractureMorphologyFileList.push({
                    uid: '-3',
                    name: data.fracture_morphology_filename,
                  })
                }
                if (data.CorrosionMorphologyFileList !== '') {
                  this.ruleForm.CorrosionMorphologyFileList.push({
                    uid: '-4',
                    name: data.corrosion_morphology_filename,
                  })
                }
                if (data.OxidationMorphologyFileList !== '') {
                  this.ruleForm.OxidationMorphologyFileList.push({
                    uid: '-5',
                    name: data.oxidation_morphology_filename,
                  })
                }
              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
          this.ruleForm.alloy_code = ''
        })
    },
    handleFinish(values) {
      this.submitting = true
      const {
        SecondPhaseFileList,
        GrainMorphologyFileList,
        FractureMorphologyFileList,
        CorrosionMorphologyFileList,
        OxidationMorphologyFileList,
      } = this.ruleForm
      const formData = new FormData()
      formData.append('sample_name', values.sample_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('organization_structure', values.organization_structure)
      // second_phase
      // grain_morphology
      formData.append('average_grain_size', values.average_grain_size)
      formData.append('second_phase_size', values.second_phase_size)
      formData.append('fracture_type', values.fracture_type)
      // fracture_morphology
      // corrosion_morphology
      // oxidation_morphology

      SecondPhaseFileList.forEach((file) => {
        // console.log(file.originFileObj)
        // console.log(file)
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file) {
          formData.append('second_phase', file.originFileObj)
        }
      })
      GrainMorphologyFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('grain_morphology', file.originFileObj)
        }
      })
      FractureMorphologyFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('fracture_morphology', file.originFileObj)
        }
      })
      CorrosionMorphologyFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('corrosion_morphology', file.originFileObj)
        }
      })
      OxidationMorphologyFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('oxidation_morphology', file.originFileObj)
        }
      })

      if (this.url !== '') {
        // 若文件列表为空，则附加属性通知后端
        if (this.ruleForm.SecondPhaseFileList.length === 0) {
          formData.append('second_phase_empty', true)
        }
        if (this.ruleForm.GrainMorphologyFileList.length === 0) {
          formData.append('grain_morphology_empty', true)
        }
        if (this.ruleForm.FractureMorphologyFileList.length === 0) {
          formData.append('fracture_morphology_empty', true)
        }
        if (this.ruleForm.CorrosionMorphologyFileList.length === 0) {
          formData.append('corrosion_morphology_empty', true)
        }
        if (this.ruleForm.OxidationMorphologyFileList.length === 0) {
          formData.append('oxidation_morphology_empty', true)
        }
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/property_management/micro_structure/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
    beforeSecondPhaseUpload(file) {
      this.ruleForm.SecondPhaseFileList = [
        ...this.ruleForm.SecondPhaseFileList,
        file,
      ]
      return false
    },
    handleSecondPhaseChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      // console.log('before:', fileList)
      fileList = fileList.slice(-1)
      // console.log('after:', fileList)
      this.ruleForm.SecondPhaseFileList = fileList
    },

    beforeGrainMorphologyUpload(file) {
      this.ruleForm.GrainMorphologyFileList = [
        ...this.ruleForm.GrainMorphologyFileList,
        file,
      ]
      return false
    },
    handleGrainMorphologyChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.GrainMorphologyFileList = fileList
    },

    beforeFractureMorphologyUpload(file) {
      this.ruleForm.FractureMorphologyFileList = [
        ...this.ruleForm.FractureMorphologyFileList,
        file,
      ]
      return false
    },
    handleFractureMorphologyChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.FractureMorphologyFileList = fileList
    },

    beforeCorrosionMorphologyUpload(file) {
      this.ruleForm.CorrosionMorphologyFileList = [
        ...this.ruleForm.CorrosionMorphologyFileList,
        file,
      ]
      return false
    },
    handleCorrosionMorphologyChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.CorrosionMorphologyFileList = fileList
    },

    beforeOxidationMorphologyUpload(file) {
      this.ruleForm.OxidationMorphologyFileList = [
        ...this.ruleForm.OxidationMorphologyFileList,
        file,
      ]
      return false
    },
    handleOxidationMorphologyChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.OxidationMorphologyFileList = fileList
    },

  },
}
</script>
